from pathlib import Path
from traceback import format_exc
from typing import Literal

from PySide6.QtCore import Signal

from .replace import WordReplaceThread
from ...base import ThreadBase
from office import word


class WordToPdfThread(ThreadBase):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.open_file = None
        self.save_file = None

    def run(self):
        try:
            word.docx2pdf(self.open_file, self.save_file)
        except Exception as e:
            self.error.emit(format_exc())

    def set_value(self, open_file, save_file):
        self.open_file = open_file
        self.save_file = save_file


class DocAndDocxThread(ThreadBase):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.openFile, self.saveFile, self._type = None, None, None

    def run(self):
        if self._type == 'doc_to_docx':
            try:
                word.doc2docx(self.openFile, self.saveFile)
            except Exception as e:
                self.error.emit(e)
        elif self._type == 'docx_to_doc':
            try:
                word.docx2doc(self.openFile, self.saveFile)
            except Exception as e:
                self.error.emit(format_exc())

    def set_value(self, openFile: str, saveFile: str, _type: Literal['doc_to_docx', 'docx_to_doc']):
        self.openFile, self.saveFile, self._type = openFile, saveFile, _type


class WordMergeThread(ThreadBase):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.openFile, self.saveFile = None, None

    def run(self):
        try:
            word.merge4docx(self.openFile, self.saveFile)
        except Exception as e:
            msg = format_exc()
            self.error.emit(msg)

    def set_value(self, openFile, saveFile):
        self.openFile, self.saveFile = openFile, saveFile


class ImgExtractThread(ThreadBase):
    progressed = Signal(str)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.column, self.saveFile = [], None

    def run(self):
        col_len = len(self.column)
        for i, v in enumerate(self.column):
            self.progressed.emit(f'正在提取 Word 文档中的图片，进度：{i + 1}/{col_len}，请稍后...')
            f = Path(self.saveFile) / 'Word文件图片'
            f.mkdir()
            try:
                word.docx4imgs(v, str(f))
            except Exception as e:
                msg = format_exc()
                self.error.emit(e)

    def set_value(self, openFile, saveFile):
        self.column, self.saveFile = openFile, saveFile
